package cn.t12.qg.userconsumer.controller;

import cn.t12.qg.userconsumer.service.LocalUserService;
import cn.t12.qg.userconsumer.vo.TokenVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qg.dto.ReturnResult;
import com.qg.dto.ReturnResultUtils;
import com.qg.pojo.QgUser;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.tomcat.util.http.parser.Authorization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@RestController
public class UserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    @Resource
    private LocalUserService localUserService;


    @PostMapping("/api/doLogin")
    public ReturnResult doLogin(String phone,String password,String token){
        TokenVo tokenVo = localUserService.login(phone, password);
        return ReturnResultUtils.returnSuccess(tokenVo);
    }

    @PostMapping("/api/v/loginOut")
    public ReturnResult logout(String token){
        localUserService.logout(token);
        return ReturnResultUtils.returnSuccess();
    }

    @Value("${login.qqAuthorizationCodeURL}")
    private String qqAuthorizationCodeURL;
    @Value("${login.qqClientId}")
    private String qqClientId;
    @Value("${login.qqRedirectUri}")
    private String qqRedirectUri;

    @GetMapping("/api/qq/login")
    public void qqLogin(HttpServletResponse response) throws IOException {

        StringBuilder builder = new StringBuilder(qqAuthorizationCodeURL);
        builder.append("&client_id="+qqClientId);
        builder.append("&redirect_uri="+ URLEncoder.encode(qqRedirectUri,"UTF-8"));
        builder.append("&state=123456");
        String qqLoginUri = builder.toString();
        if(LOGGER.isDebugEnabled()){
            LOGGER.debug("重定向qq登录uri:[{}]",qqLoginUri);
        }

        response.sendRedirect(qqLoginUri);
    }


    @Value("${login.qqAccessTokenUri}")
    private String qqAccessTokenUri;
    
    @Value("${login.qqClientSecret}")
    private String qqClientSecret;

    @Value("${login.successRedirectUrl}")
    private String successRedirectUrl;

    // qq通知浏览器重定向到项目中的
    @GetMapping("/api/login")
    public void qqLoingCallback(String code ,String state,HttpServletResponse response) throws IOException {
        // 获取 accessToken
        String accessTokenUri = biuldAccessTokenUri(code);
        LOGGER.info("accessTokenUri:[ {} ]",accessTokenUri);
        String accessTokenUriResult = getFromUri(accessTokenUri);
        LOGGER.info("accessTokenUriResult:[ {} ]",accessTokenUriResult);
        JSONObject accessTokenJsonResult = JSON.parseObject(accessTokenUriResult);
        String accessToken = accessTokenJsonResult.get("access_token").toString();
        // 获取 openId
        String OpenIDUri = biuldOpenIDUri(accessToken);
        LOGGER.info("OpenIDUri:[ {} ]",OpenIDUri);
        String OpenIDUriResult = getFromUri(OpenIDUri);
        LOGGER.info("OpenIDUriResult:[ {} ]",OpenIDUriResult);
        JSONObject OpenIDJsonResult = JSON.parseObject(OpenIDUriResult);
        String openId= OpenIDJsonResult.get("openid").toString();
        // 根据openId查询用户信息
        boolean exists = localUserService.exists(openId);
        if (!exists) {
            // 根据openid获取用户信息
            String getUserInfoUri = biuldGetUserInfoUri(accessToken,openId);
            LOGGER.info("getUserInfoUri:[ {} ]",getUserInfoUri);
            String getUserInfoResult = getFromUri(getUserInfoUri);
            LOGGER.info("getUserInfoResult:[ {} ]",getUserInfoResult);
            JSONObject getUserInfoJsonResult = JSON.parseObject(getUserInfoResult);

            // 注册
            QgUser qgUser = new QgUser();
            qgUser.setId(openId);
            qgUser.setRealName(getUserInfoJsonResult.get("nickname").toString());
            qgUser.setWxUserId(openId);

            localUserService.register(qgUser);
        }
        // 登录
        TokenVo tokenVo = localUserService.loginByOpenId(openId);
        // 返回结果
        response.sendRedirect(successRedirectUrl+tokenVo.getToken());

    }

    @Value("${login.qqGetUserInfoUri}")
    private String qqGetUserInfoUri;
    private String biuldGetUserInfoUri(String accessToken, String openId) {
        StringBuilder builder = new StringBuilder(qqGetUserInfoUri);
        builder.append("?access_token="+accessToken);
        builder.append("&oauth_consumer_key="+qqClientId);
        builder.append("&openid="+openId);
        return builder.toString();
    }

    @Value("${login.qqOpenIdUri}")
    private String qqOpenIdUri;
    private String biuldOpenIDUri(String accessToken) {
        StringBuilder builder = new StringBuilder(qqOpenIdUri);
        builder.append("&access_token="+accessToken);
        return builder.toString();
    }

    private String biuldAccessTokenUri(String code) throws UnsupportedEncodingException {
        StringBuilder builder = new StringBuilder(qqAccessTokenUri);
        builder.append("&client_id="+qqClientId);
        builder.append("&client_secret="+qqClientSecret);
        builder.append("&code="+code);
        builder.append("&redirect_uri="+ URLEncoder.encode(qqRedirectUri,"UTF-8"));
        return  builder.toString();
    }

    private String getFromUri(String uri) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(uri);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        try {
            HttpEntity entity = response.getEntity();
            return  EntityUtils.toString(entity);
        } finally {
            response.close();
            httpclient.close();
        }
    }
}
